#!/usr/bin/env python3
import gpiod
import time

# 常量定义（模拟宏）
GPIO_CHIP = 'gpiochip0'
GPIO23_LINE_OFFSET = 23  # GPIO23在gpiochip0中的偏移量
GPIO24_LINE_OFFSET = 24  # GPIO24在gpiochip0中的偏移量
SAMPLE_DELAY = 0.5  # 采样延迟时间（秒）

def setup_gpio_lines():
    """设置GPIO输入线路"""
    try:
        # 打开GPIO芯片
        chip = gpiod.Chip(GPIO_CHIP)
        
        # 获取GPIO线路
        lines = chip.get_lines([GPIO23_LINE_OFFSET, GPIO24_LINE_OFFSET])
        
        # 设置为输入模式
        lines.request(consumer='gpio_input_detector', type=gpiod.LINE_REQ_DIR_IN)
        
        return chip, lines
    except Exception as e:
        print(f"设置GPIO时出错: {e}")
        return None, None

def read_gpio_values(lines):
    """读取GPIO值"""
    if lines is None:
        return None, None
    
    values = lines.get_values()
    return values[0], values[1]

def print_gpio_values(value23, value24):
    """打印GPIO值"""
    print(f"GPIO23: {value23} ({'高电平' if value23 == 1 else '低电平'}), "
          f"GPIO24: {value24} ({'高电平' if value24 == 1 else '低电平'})")

def main():
    """主函数"""
    chip, lines = None, None
    
    try:
        print("初始化GPIO设置...")
        chip, lines = setup_gpio_lines()
        
        if chip is None or lines is None:
            print("无法初始化GPIO，退出程序")
            return
        
        print("开始读取GPIO23和GPIO24的值（按下Ctrl+C退出）...")
        print("=" * 50)
        
        while True:
            # 读取GPIO值
            value23, value24 = read_gpio_values(lines)
            
            # 打印值
            print_gpio_values(value23, value24)
            
            # 等待一段时间
            time.sleep(SAMPLE_DELAY)
            
    except KeyboardInterrupt:
        print("\n用户中断程序")
    except Exception as e:
        print(f"发生错误: {e}")
    finally:
        print("清理GPIO资源...")
        if lines is not None:
            lines.release()
        if chip is not None:
            chip.close()
        print("程序结束")

if __name__ == "__main__":
    main()